﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharepointSolutionInstaller.Views;
using SharepointSolutionInstaller.Resources;
using Microsoft.SharePoint.Administration;
using System.Security;
using System.IO;
using System.Data.SqlClient;
using SharepointSolutionInstaller.Utils.Configuration;

namespace SharepointSolutionInstaller.Utils.SolutionDeployment
{

    /// <summary>
    /// Command for adding the SharePoint solution.
    /// </summary>
    public class AddSolutionCommand : SolutionCommand
    {
        string fileName;
        Guid solutionId;
        internal AddSolutionCommand(InstallProcess parent, string fileName,Guid solutionId)
            : base(parent)
        {
            this.fileName = fileName;
            this.solutionId = solutionId;
        }

        internal override string Description
        {
            get
            {
                return CommonUIStrings.addSolutionCommand;
            }
        }

        protected internal override bool Execute()
        {

            if (String.IsNullOrEmpty(fileName))
            {
                throw new Exception(CommonUIStrings.installExceptionConfigurationNoWsp);
            }

            try
            {
                SPFarm farm = SPFarm.Local;
                SPSolution solution = farm.Solutions.Add(fileName);
                return true;
            }

            catch (SecurityException ex)
            {
                string message = CommonUIStrings.addSolutionAccessError;
                if (Environment.OSVersion.Version >= new Version("6.0"))
                    message += " " + CommonUIStrings.addSolutionAccessErrorWinServer2008Solution;
                else
                    message += " " + CommonUIStrings.addSolutionAccessErrorWinServer2003Solution;
                throw new Exception(message, ex);
            }

            catch (IOException ex)
            {
                throw new Exception(ex.Message, ex);
            }

            catch (ArgumentException ex)
            {
                throw new Exception(ex.Message, ex);
            }

            catch (SqlException ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }

        protected internal override bool Rollback()
        {
            RemoveSolution(solutionId);
            return true;
        }
    }
}
